import * as axios from 'axios'
// import cookie from 'react-cookies'
import config from './config'

export default {
    // called when the user attempts to log in
    login: async (params) => {
        localStorage.setItem('username', params.username);
        // accept all username/password combinations
        let res = await axios.post(config.base_url + '/login', params)
        console.log(res)
        if (res.data.code == 0 && res.data.token) {
            // cookie.save('token', res.data.token, { path: '/' })
            localStorage.setItem('token', res.data.token);
            return Promise.resolve();
        } else {
            return Promise.reject();
        }
    },
    // called when the user clicks on the logout button
    logout: () => {
        localStorage.removeItem('username');
        return Promise.resolve();
    },
    // called when the API returns an error
    checkError: ({ status }) => {
        if (status === 401 || status === 403) {
            localStorage.removeItem('username');
            return Promise.reject();
        }
        return Promise.resolve();
    },
    // called when the user navigates to a new location, to check for authentication
    checkAuth: () => {
        return localStorage.getItem('username')
            ? Promise.resolve()
            : Promise.reject();
    },
    // called when the user navigates to a new location, to check for permissions / roles
    getPermissions: () => Promise.resolve(),
};
